package com.wan.util.cglib;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import net.sf.cglib.reflect.FastClass;
import net.sf.cglib.reflect.FastMethod;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 基于cglib的FastClass，基于字节码操作，比传统反射调用性能更好
 */
@SuppressWarnings("unchecked")
public class FastClassUtil {

    private static final Map<Class<?>, FastClass> FAST_CLASS_MAP = new HashMap<>();
    private static final Map<Method, FastMethod> FAST_METHOD_MAP = new HashMap<>();
    private static final Map<Field, FastField> FAST_FIELD_MAP = new HashMap<>();

    public static FastClass getFastClass(Class<?> cls){
        return FAST_CLASS_MAP.computeIfAbsent(cls,FastClass::create);
    }

    public static FastMethod getFastMethod(Method method){
        return FAST_METHOD_MAP.computeIfAbsent(method,m->{
            FastClass fastClass = getFastClass(method.getDeclaringClass());
            return fastClass.getMethod(method);
        });
    }

    public static FastField getFastField(Field field){
        return FAST_FIELD_MAP.computeIfAbsent(field, FastField::new);
    }

    /**
     * 创建一个指定类型的实例，依赖无参构造方法
     */
    public static  <T> T newInstance(Class<T> cls) {
        FastClass fastClass = getFastClass(cls);
        try {
            return (T) fastClass.newInstance();
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}
